package com.cahnggou.web.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.order.feign.CartFeign;
import com.changgou.order.feign.OrderFeign;
import com.changgou.order.pojo.Order;
import com.changgou.order.pojo.OrderItem;
import com.changgou.user.feign.AddressFeign;
import com.changgou.user.pojo.Address;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 戴金华
 * @date 2019-12-18 11:15
 */
@Controller
@CrossOrigin
@RequestMapping("/worder")
public class OrderController {

    @Autowired
    private AddressFeign addressFeign;

    @Autowired
    private CartFeign cartFeign;

    @Autowired
    private OrderFeign orderFeign;



    /**
     * 显示订单结算页面
     * @param model
     * @return
     */
    @RequestMapping("/ready/order")
    public String readyOrder(Model model){
        List<Address> addressList = addressFeign.list().getData();
        model.addAttribute("addressList",addressList);


        //找出默认的收货地址
        for (Address address : addressList) {
            if ("1".equals(address.getIsDefault())){
                model.addAttribute("defaultAddr",address);
                break;
            }
        }
        List<Map<String, Object>> cartList = cartFeign.list();
        ArrayList<OrderItem> orderItems = new ArrayList<>();
        Integer totalNum = 0;
        Integer totalMoney = 0;

        //找出那些选中的购物车商品
        for (Map<String, Object> map : cartList) {
            boolean checked = (boolean) map.get("checked");
            if (checked){
                //如果该项被选中 将总数量和总价格添加进去
                ObjectMapper mapper = new ObjectMapper();
                OrderItem orderItem = mapper.convertValue(map.get("item"), OrderItem.class);
                totalMoney+=orderItem.getMoney();
                totalNum+=orderItem.getNum();
                orderItems.add(orderItem);
            }
        }

        model.addAttribute("orderItems",orderItems);
        model.addAttribute("totalNum",totalNum);
        model.addAttribute("totalMoney",totalMoney);
        return "order";
    }

    /**
     * 添加订单数据
     * @param order
     * @return
     */
    @PostMapping
    @ResponseBody
    public Result add(@RequestBody Order order){
        //用户名暂时写死
        order.setUsername("heima");
        String orderId = (String) orderFeign.add(order).getData();
        return new Result(true, StatusCode.OK,"订单添加成功",orderId);
    }

}
